package com.jn.okhttp.views;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.jn.okhttp.R;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class DataDisplayActivity extends AppCompatActivity {
    private TextView resultTextView;
    private static final String TAG = "DataDisplayActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_display);

        resultTextView = findViewById(R.id.text_view_result);
        String url = getIntent().getStringExtra("url");
        if (url != null) {
            fetchData(url);
        }
    }

    private void fetchData(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "请求失败: ", e);
                runOnUiThread(() -> resultTextView.setText("请求失败，请稍后重试。"));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    runOnUiThread(() -> resultTextView.setText(responseData));
                } else {
                    Log.e(TAG, "请求失败: " + response.message());
                    runOnUiThread(() -> resultTextView.setText("请求失败，请稍后重试。"));
                }
            }
        });
    }
}
